package com.sxjh.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.common.ResultException;
import com.sxjh.entity.Task;
import com.sxjh.entity.param.ReportsDetailParam;
import com.sxjh.entity.param.ReportsListParam;
import com.sxjh.entity.result.PlanedTaskListResult;
import com.sxjh.entity.result.TaskListResult;
import com.sxjh.enums.NodeEnum;
import com.sxjh.mapper.TaskMapper;
import com.sxjh.service.FileService;
import com.sxjh.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 任务  服务实现类
 * </p>
 *
 * @author zixin
 * @since 2021-06-06
 */
@Slf4j
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private FileService fileService;

    @Override
    public IPage<TaskListResult> list(IPage iPage, TaskListResult param) {
        IPage<TaskListResult> taskPage = taskMapper.list(iPage, param);
        if (taskPage != null && CollUtil.isNotEmpty(taskPage.getRecords())) {
            //根据装卸货点是否配置显示下一个节点
            taskPage.getRecords().forEach(p -> {
                int currNode = p.getCurrNode();
                int nextNode = currNode;
                String nextNodeName = "";
                if (currNode == 1) {
                    //过初磅
                    if (1 == p.getUpPhotoFlag()) {
                        //不需要拍照
                        nextNode = nextNode + 2;
                    } else {
                        nextNode = nextNode + 1;
                    }
                    nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                } else if (currNode == 2) {
                    //装车点拍照
                    nextNode = nextNode + 1;
                    nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                } else if (currNode == 3) {
                    //过复磅
                    int downPhotoFlag = p.getDownPhotoFlag();
                    int downConfirmFlag = p.getDownConfirmFlag();
                    if (downPhotoFlag == 1 && downConfirmFlag == 1) {
                        //不需要拍照，不需要签字，没有下一节点
                        nextNode = 0;
                        nextNodeName = "";
                    } else if (downPhotoFlag == -1 && downConfirmFlag == -1) {
                        //需要拍照，需要签字
                        nextNode = nextNode + 1;
                        nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                    } else if (downPhotoFlag == 1 && downConfirmFlag == -1) {
                        //不需要拍照，需要签字
                        nextNode = nextNode + 2;
                        nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                    } else {
                        //需要拍照，不需要签字
                        nextNode = nextNode + 1;
                        nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                    }
                    nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                } else if (currNode == 4) {
                    //卸车点拍照
                    if (1 == p.getDownConfirmFlag()) {
                        //不需要签字
                        nextNode = 0;
                        nextNodeName = "";
                    } else {
                        nextNode = nextNode + 1;
                        nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                    }
                } else if (currNode == 5) {
                    //卸车点签字确认
                    nextNode = 0;
                    nextNodeName = "";
                } else {
                    //未执行
                    nextNode = 1;
                    nextNodeName = NodeEnum.getCurrNodeName(nextNode);
                }
                p.setNextNode(nextNode);
                p.setNextNodeName(nextNodeName);
                if (StrUtil.isNotBlank(p.getTare())) {
                    //KG->t
                    p.setTare((new BigDecimal(p.getTare())).divide(BigDecimal.valueOf(1000L)).toString());
                }
                if (StrUtil.isNotBlank(p.getGross())) {
                    //KG->t
                    p.setGross((new BigDecimal(p.getGross())).divide(BigDecimal.valueOf(1000L)).toString());
                }
            });
        }
        return taskPage;
    }

    @Override
    public TaskListResult list(Integer vehId) {
        return taskMapper.list2(vehId);
    }

    @Override
    public List<PlanedTaskListResult> taskList(String icNumber, Integer status) {
        return taskMapper.taskList(icNumber, status);
    }

    @Override
    public IPage<ReportsListParam> reportList(IPage iPage, ReportsListParam param) {
        IPage<ReportsListParam> page = taskMapper.reportList(iPage, param);
        if (page != null && CollUtil.isNotEmpty(page.getRecords())) {
            List<ReportsListParam> list = page.getRecords();
            list.forEach(p -> {
                //KG->t
                if (p.getTareCount() != null) {
                    p.setTareCount((new BigDecimal(p.getTareCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                if (p.getGrossCount() != null) {
                    p.setGrossCount((new BigDecimal(p.getGrossCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                if (p.getNetCount() != null) {
                    p.setNetCount((new BigDecimal(p.getNetCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            });
        }
        return page;
    }

    @Override
    public IPage<ReportsDetailParam> reportDetail(IPage iPage, ReportsDetailParam param) {
        IPage<ReportsDetailParam> page = taskMapper.reportDetail(iPage, param);
        if (page != null && CollUtil.isNotEmpty(page.getRecords())) {
            List<ReportsDetailParam> list = page.getRecords();
            list.forEach(p -> {
                //KG->t
                //KG->t
                if (p.getTareCount() != null) {
                    p.setTareCount((new BigDecimal(p.getTareCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                if (p.getGrossCount() != null) {
                    p.setGrossCount((new BigDecimal(p.getGrossCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                if (p.getNetCount() != null) {
                    p.setNetCount((new BigDecimal(p.getNetCount())).divide(BigDecimal.valueOf(1000L)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            });
        }
        return page;
    }

    @Override
    @Async(value = "taskExecutor")
    public void savePhpFile(int id, MultipartFile file1, MultipartFile file2, boolean isFirst) {
        String img1 = null;
        String img2 = null;
        try {
            CompletableFuture<String> img11 = fileService.savePhpFile(file1);
            CompletableFuture<String> img22 = fileService.savePhpFile(file2);
            CompletableFuture.allOf(img11, img22).join();
            img1 = img11.get();
            img2 = img22.get();
        } catch (ResultException | IOException | ExecutionException | InterruptedException e) {
            //throw new RuntimeException(e);
            log.error("过磅上传图片异常:{}", e.getMessage());
        }
        log.info("异步更新过磅上传图片img1:{}", img1);
        log.info("异步更新过磅上传图片img2:{}", img2);
        if (StrUtil.isNotBlank(img1)) {
            Task task = taskMapper.selectById(id);
            if (isFirst) {
                task.setTareImg(img1);
                task.setTareImgTwo(img2);
            } else {
                task.setGrossImg(img1);
                task.setGrossImgTwo(img2);
            }
            log.info("异步更新过磅上传图片:{}", JSONUtil.toJsonStr(task));
            updateById(task);
        }
    }

    @Override
    public void updateTaskById(Task task) {
        taskMapper.updateTaskById(task);
    }


}
